package br.com.gscorp.bankLion.security;

import java.io.IOException;
import java.io.StringWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;


@Component
public class BankLionAuthenticationSuccessHandler implements
		AuthenticationSuccessHandler {
	
	@Autowired
	private JsonFactory jsonFactory;
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		
		request.getSession().setMaxInactiveInterval(60*60);
		
		StringWriter writer = new StringWriter();
		JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer);
		
		Object principal = authentication.getPrincipal();
		if (BankLionUserDetails.class.isAssignableFrom(principal.getClass())) {
			BankLionUserDetails details = (BankLionUserDetails) principal;
			jsonGenerator.writeObject(details);
		}
		
		this.updateHeaders(response);
		
		try {
			response.getWriter().print(writer.toString());
			response.getWriter().flush();
		} finally {
			writer.close();
		}
	}

	private void updateHeaders(HttpServletResponse response) {
		response.setHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE);
	}

}
